import json

from sqlalchemy import event, func
from flask_login import current_user

from instance.app_instance import app
import utils.archive_helper as ar
from models.sync_model import SyncModel

import gevent

def add_sync_record(type, dump_data, user_id):
    stringified_data = json.dumps(dump_data)
    app.db.session.add(SyncModel(create_t=func.now(), type=type, model=stringified_data, user_id=user_id))
    app.db.session.commit()

@event.listens_for(app.db.Model, 'after_delete', propagate=True)
def receive_after_delete(mapper, connection, target):
    if target.__class__.__name__ in app.ignored_models:
        return
    dump_data = ar.to_json(target)
    gevent.spawn(add_sync_record, 'delete', dump_data, current_user.get_id() if current_user else '')

@event.listens_for(app.db.Model, 'after_insert', propagate=True)
def receive_after_insert(mapper, connection, target):
    if target.__class__.__name__ in app.ignored_models:
        return
    dump_data = ar.to_json(target)
    gevent.spawn(add_sync_record, 'insert', dump_data, current_user.get_id() if current_user else '')

@event.listens_for(app.db.Model, 'after_update', propagate=True)
def receive_after_update(mapper, connection, target):
    if target.__class__.__name__ in app.ignored_models:
        return
    dump_data = ar.to_json(target)
    gevent.spawn(add_sync_record, 'update', dump_data, current_user.get_id() if current_user else '')

@event.listens_for(app.db.session, 'after_bulk_update')
def receive_after_bulk_update(update_context):
    "listen for the 'after_bulk_update' event"
    for m in update_context.matched_objects:
        if m.__class__.__name__ in app.ignored_models:
            continue
        dump_data = ar.to_json(m)
        gevent.spawn(add_sync_record, 'update', dump_data, current_user.get_id() if current_user else '')


